"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@angular-devkit/core");
const schematics_1 = require("@angular-devkit/schematics");
const fse = require("fs-extra");
const source_root_helpers_1 = require("../../utils/source-root.helpers");
const defaults_1 = require("../defaults");
function main(options) {
    // const appName = getAppNameFromPackageJson();
    options = transform(options);
    options.packageName = core_1.strings.dasherize(`${options.name}`);
    return schematics_1.chain([
        updateCpaasConfig(options, options.packageName),
        schematics_1.branchAndMerge(schematics_1.mergeWith(generate(options))),
    ]);
}
exports.main = main;
function getAppNameFromPackageJson() {
    try {
        if (!fse.existsSync('./package.json')) {
            return defaults_1.DEFAULT_DIR_ENTRY_APP;
        }
        const packageJson = fse.readJsonSync('./package.json');
        if (!packageJson.name) {
            return defaults_1.DEFAULT_DIR_ENTRY_APP;
        }
        let name = packageJson.name;
        name = name.replace(/[^\w.]+/g, '-').replace(/\-+/g, '-');
        return name[0] === '-' ? name.substr(1) : name;
    }
    catch (_a) {
        return defaults_1.DEFAULT_DIR_ENTRY_APP;
    }
}
function transform(options) {
    const target = Object.assign({}, options);
    const defaultSourceRoot = options.rootDir !== undefined ? options.rootDir : defaults_1.DEFAULT_PACKAGES_PATH;
    if (!target.name) {
        throw new schematics_1.SchematicsException('Option (name) is required.');
    }
    target.language = !!target.language ? target.language : defaults_1.DEFAULT_LANGUAGE;
    target.name = core_1.strings.dasherize(target.name);
    target.path =
        target.path !== undefined
            ? core_1.join(core_1.normalize(defaultSourceRoot), target.path)
            : core_1.normalize(defaultSourceRoot);
    return target;
}
function updateJsonFile(host, path, callback) {
    const source = host.read(path);
    if (source) {
        const sourceText = source.toString('utf-8');
        const json = core_1.parseJson(sourceText);
        callback(json);
        host.overwrite(path, JSON.stringify(json, null, 2));
    }
    return host;
}
function updateCpaasConfig(options, defaultAppName) {
    return (host) => {
        if (!host.exists('.cpaasrc.json')) {
            host.create('.cpaasrc.json', '{ "packages": [] }');
        }
        return updateJsonFile(host, '.cpaasrc.json', (cpaasrc) => {
            if (cpaasrc.packages &&
                cpaasrc.packages.find(item => item.name === options.packageName)) {
                return cpaasrc;
            }
            cpaasrc.packages = [
                {
                    name: options.packageName,
                },
                ...(cpaasrc.packages || []),
            ];
            return cpaasrc;
        });
    };
}
function updatePackageJson(options, defaultAppName) {
    return (host) => {
        if (!host.exists('package.json')) {
            return host;
        }
        return updateJsonFile(host, 'package.json', (packageJson) => {
            // updateNpmScripts(packageJson.scripts, options, defaultAppName);
            updateDependencies(packageJson.dependencies, options, defaultAppName);
            // updateJestOptions(packageJson.jest, options);
        });
    };
}
function updateDependencies(scripts, options, defaultAppName) {
    scripts[options.packageName] = '0.0.1';
}
function generate(options) {
    const path = core_1.join(options.path, options.packageName);
    return schematics_1.apply(schematics_1.url(core_1.join('./files', options.language)), [
        schematics_1.template(Object.assign(Object.assign({}, core_1.strings), options)),
        schematics_1.move(path),
        source_root_helpers_1.removeTemplateExt(),
    ]);
}
